package com.example.excel.ui.fragment.setting;

import android.text.TextUtils;
import android.view.View;

import com.example.excel.R;
import com.example.excel.base.BaseFragment;
import com.example.excel.config.Constants;
import com.example.excel.databinding.FragmentSettingBinding;
import com.example.excel.http.HttpManager;
import com.example.excel.utils.SharedPreferencesUtils;
import com.example.excel.utils.Utils;

import androidx.lifecycle.ViewModelProviders;

public class SettingFragment extends BaseFragment<FragmentSettingBinding, SettingViewModel> {

    @Override
    protected Class<SettingViewModel> initViewModel() {
        return SettingViewModel.class;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_setting;
    }

    @Override
    protected void initView() {
        mBinding.setViewModel(mViewModel);
        String string = SharedPreferencesUtils.getString(Constants.SP_BASE_URL_HTTP, "");
        String stringPort = SharedPreferencesUtils.getString(Constants.SP_BASE_URL_HTTP_PORT, "");
        if(TextUtils.isEmpty(string)){
            string = "192.168.0.96";
            stringPort = "8080";
            SharedPreferencesUtils.setString(Constants.SP_BASE_URL_HTTP, string);
            SharedPreferencesUtils.setString(Constants.SP_BASE_URL_HTTP_PORT, stringPort);
        }
        mBinding.etCode.setText(string);
        mBinding.etCodePort.setText(stringPort);

        mBinding.btnSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onRefreshBaseUrl();
            }
        });
    }

    @Override
    protected void lazyInit() {

    }

    public void onRefreshBaseUrl() {
        String http = mBinding.etCode.getText().toString().trim();
        String httpPort = mBinding.etCodePort.getText().toString().trim();
        if(!TextUtils.isEmpty(http) && !TextUtils.isEmpty(httpPort)){
            SharedPreferencesUtils.setString(Constants.SP_BASE_URL_HTTP, http);
            SharedPreferencesUtils.setString(Constants.SP_BASE_URL_HTTP_PORT, httpPort);
            HttpManager.getInstance().init("http://" + http + ":" + httpPort + "/");
        } else {
            Utils.getInstance().showToast("请输入IP地址或端口号");
        }
    }
}
